package net.qhzw.admin.config;

import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import net.qhzw.admin.constant.AuthConstant;
import net.qhzw.admin.constant.MessageConstant;
import net.qhzw.admin.domain.UserDto;
import net.qhzw.admin.entity.SysPermission;
import net.qhzw.admin.entity.SysRole;
import net.qhzw.admin.entity.SysUser;
import net.qhzw.admin.mapper.PermissionMapper;
import net.qhzw.admin.mapper.SysPermissionMapper;
import net.qhzw.admin.mapper.SysRoleMapper;
import net.qhzw.admin.mapper.SysUserMapper;
import net.qhzw.admin.model.LoginUser;
import net.qhzw.admin.model.SecurityUser;
import net.qhzw.admin.model.UserInfo;
import net.qhzw.admin.pojo.SysUserVo;
import net.qhzw.admin.service.UmsAdminService;
import net.qhzw.common.exception.CustomException;
import net.qhzw.common.model.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
@Slf4j
public class JwtUserDetailsService implements UserDetailsService {


    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            SysUserVo user = userMapper.selectByUsername(username);
            checkUser(user, username);
            if (user.getStatus() == 0) {
                log.info("登录用户：{} 已锁定", username);
                throw new CustomException("登录用户：" + username + " 已锁定请联系管理员", 501);
            }
            return getUserDetails(user);
        } catch (CustomException e) {
            log.error("登录异常: {}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        } catch (Exception e) {
            log.error("登录异常: {}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    private UserDetails getUserDetails(SysUserVo user) {
        try {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            if (user.getRoleId() != null && !StringUtils.isEmpty(user.getRoleId())) {
                SysRole sysRole = roleMapper.selectByPrimaryKey(user.getRoleId());
                if (sysRole != null) {
                    userDto.setRoles(Arrays.asList(sysRole.getCode()));
                    List<SysPermission> permissions = permissionMapper.selectByRoleKey(sysRole.getId());
                    if (permissions != null && !permissions.isEmpty()) {
                        List<String> codes = new ArrayList<>();
                        for (SysPermission permission : permissions) {
                            codes.add(permission.getCode());
                        }
                        userDto.setPermissions(codes);
                    }
                }
            }
            return new SecurityUser(userDto);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public void checkUser(SysUserVo user, String username) {
        if (user == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
    }


}
